/*
 * Copyright 2011 CraneLeeon authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.crane.webtemplate.action.security;


import org.crane.webtemplate.action.BaseAction;
import org.crane.webtemplate.action.BaseAction.UpdatePriciple;
import org.crane.webtemplate.exception.TextMessageException;
import org.crane.webtemplate.dao.security.UserDAO;
import org.crane.webtemplate.model.security.User;
import java.util.Arrays;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.hibernate.exception.ConstraintViolationException;
import org.json.JSONObject;
import static org.crane.webtemplate.Tokens.*;

/**
 *
 * @author CraneLeeon
 */
@Action("/security/UserMgt")
@Results({
    @Result(name = "page", type = "dispatcher", location = "UserMgt.jsp"),
    @Result(name = "json", type = "dispatcher", location = "/WEB-INF/jsp/json.jsp"),
    @Result(name = "xml", type = "dispatcher", location = "/WEB-INF/jsp/xml.jsp")
})
public class UserMgt extends BaseAction{

    protected static final Log logger = LogFactory.getLog(UserMgt.class);

    @Override
    public  Class getBoClass(){
        return User.class;
    }

    @Override
    public String execute() throws Exception {
        try {
            switch (this.act) {
                case ACT_SAVE:
                    this.save();break;
                case ACT_DELETE:
                    this.delete();break;
                default: return "page";
            }
        } catch (TextMessageException ex) {
            this.json = new JSONObject()
                    .put("success", false)
                    .put("info", (ex.getPrefixMessage()==null? "":ex.getPrefixMessage())+getText(ex.getMessage())+(ex.getSuffixMessage()==null? "":ex.getSuffixMessage()))
                    .toString();
        } catch (ConstraintViolationException ex) {
            logger.debug(ex);
            this.json = new JSONObject().put("success", false).put("info", getText("ConstraintViolationException")).toString();
        } catch (Exception ex) {
            logger.debug(ex);
            this.json = new JSONObject().put("success", false).put("info", ex).toString();
        }
        return "json";
    }

    @Override
    protected void save() throws Exception {
        UserDAO dao = new UserDAO();
        JSONObject jobj = new JSONObject().put("success", true).put("info","");
        dao.startTransaction();
        try {
            User obj = (User) this.getDummy(this.getBoClass(), 
                    UpdatePriciple.ALLOWABLE_ORIENTED,
                    Arrays.asList(
                        "password"
                    ));
            dao.createOrUpdate(obj);
            jobj.put("id", obj.getId());
            //if want to send more info to the browser write them here as jobj.put(...,...);
            dao.commitTransaction();
        } catch (Exception ex) {
            dao.rollbackTransaction();
            throw ex;
        }
        this.json = jobj.toString();
    }

}
